package timing.ukulele.storage.filter;

import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import timing.ukulele.common.data.ResponseCode;
import timing.ukulele.common.data.ResponseData;
import timing.ukulele.common.util.JsonUtils;
import timing.ukulele.storage.config.SecurityProperties;
import timing.ukulele.storage.jwt.JWTProvider;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.LinkedHashMap;

@Component
@Slf4j
public class LoginFilter implements Filter {

    private final JWTProvider jwtProvider;
    private final SecurityProperties securityProperties;

    public LoginFilter(JWTProvider jwtProvider,
                       SecurityProperties securityProperties) {
        this.jwtProvider = jwtProvider;
        this.securityProperties = securityProperties;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse httpServletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        String token = req.getHeader("token");
        if (token != null) {
            log.info("auth success");
            Claims userFromToken = jwtProvider.getUserFromToken(token);
            if (userFromToken != null) {
                HeaderMapRequestWrapper wrapper = new HeaderMapRequestWrapper((HttpServletRequest) request);
                wrapper.addHeader("account", userFromToken.getSubject());
                LinkedHashMap user = userFromToken.get("user", LinkedHashMap.class);
                ArrayList authorities = (ArrayList) user.get("authorities");
                if (!CollectionUtils.isEmpty(authorities)) {
                    LinkedHashMap authMap = (LinkedHashMap) authorities.get(0);
                    wrapper.addHeader("role", (String) authMap.get("authority"));
                }
                chain.doFilter(wrapper, httpServletResponse);
            }
        } else {
            chain.doFilter(request, httpServletResponse);
        }
    }

    private void failure(ServletResponse httpServletResponse) throws IOException {
        HttpServletResponse response = (HttpServletResponse) httpServletResponse;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Cache-Control", "no-cache");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        ResponseData<String> data = new ResponseData<>(ResponseCode.PARA_ERROR, "无权限");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        PrintWriter writer = httpServletResponse.getWriter();
        String dataString = JsonUtils.deserializer(data);
        writer.println(dataString);
        writer.flush();
    }
}
